package io.rong.app.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.yunshipei.adapter.PagerChangeAdapter;
import com.yunshipei.common.manager.EnterConfig;
import com.yunshipei.db.DatabaseUtil;
import com.yunshipei.enterplorer.R;
import com.yunshipei.inter.ContactsRefreshCallBack;
import com.yunshipei.model.MainExtraBean;
import com.yunshipei.model.UserInfo;
import com.yunshipei.ui.activity.SeekContactsActivity;
import com.yunshipei.ui.fragment.BaseNavItemFragment;
import com.yunshipei.ui.fragment.ContactsToFragment;
import com.yunshipei.ui.fragment.DepartmentFragment;
import com.yunshipei.ui.view.SimpleSwipeRefreshLayout;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class ContactsFragment extends BaseNavItemFragment implements ContactsRefreshCallBack {

    private static final String ARGS_CONTACTS_MAIN_DATA = "com.enterplorer.main.data";

    @Bind(R.id.swipe_container)
    protected SimpleSwipeRefreshLayout mRefreshView;
    @Bind(R.id.pager)
    protected ViewPager pager;
    @Bind(R.id.tv_company_name)
    protected TextView tvCompanyName;
    @Bind(R.id.iv_right_icon)
    protected ImageView ivRightIcon;
    @Bind(R.id.title_bar_content)
    protected RelativeLayout rlTitleContent;
    @Bind(R.id.tab_layout)
    protected TabLayout tlTabs;

    private Context mContext;

    private boolean contactsToRefreshFinished = false;
    private boolean departmentRefreshFinished = false;

    private Fragment[] fragments = new Fragment[2];
    private MainExtraBean mMainExtraBean;

    public static ContactsFragment newInstances(MainExtraBean mainExtraBean) {
        ContactsFragment contactsFragment = new ContactsFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(ARGS_CONTACTS_MAIN_DATA, mainExtraBean);
        contactsFragment.setArguments(bundle);
        return contactsFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.mContext = getActivity();
        this.mMainExtraBean = (MainExtraBean) getArguments().getSerializable(ARGS_CONTACTS_MAIN_DATA);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.contacts_fragment_list, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        tvCompanyName.setText(mMainExtraBean.getCompanyTitle());
        rlTitleContent.setBackgroundColor(EnterConfig.getInstance().getGlobalColor());
        ivRightIcon.setImageResource(R.drawable.search);
        ivRightIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DatabaseUtil dbUtil = new DatabaseUtil();
                //数据库查询所有联系人
                List<UserInfo> list = dbUtil.queryAll();
                if (list.size() <= 0) {
                    Toast.makeText(mContext, "获取通信录失败", Toast.LENGTH_LONG).show();
                } else {
                    Intent it = new Intent();
                    it.setClass(mContext, SeekContactsActivity.class);
                    startActivity(it);
                }
            }
        });
        mRefreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                contactsToRefreshFinished = false;
                departmentRefreshFinished = false;
                if (fragments[0] != null && fragments[1] != null) {
                    ((ContactsToFragment) fragments[0]).getUsualUserList();
                    ((DepartmentFragment) fragments[1]).fetchDepartmentData();
                }
            }
        });
        pager.addOnPageChangeListener(new PagerChangeAdapter() {
            @Override
            public void onPageScrollStateChanged(int state) {
                enableDisableSwipeRefresh(state == ViewPager.SCROLL_STATE_IDLE);
            }
        });
        mRefreshView.setViewPager(pager);
        fragments[0] = getFragmentManager().findFragmentByTag("android:switcher:" + R.id.pager + ":0");
        fragments[1] = getFragmentManager().findFragmentByTag("android:switcher:" + R.id.pager + ":1");
        if (fragments[0] == null) {
            fragments[0] = ContactsToFragment.newInstances();
        }
        if (fragments[1] == null) {
            fragments[1] = DepartmentFragment.newInstances(true);
        }
        ((ContactsToFragment) fragments[0]).setRefreshCallBack(this);
        ((DepartmentFragment) fragments[1]).setRefreshCallBack(this);
        pager.setAdapter(new FragmentPagerAdapter(getFragmentManager()) {

            private final String[] title = new String[]{"常用", "同事"};

            @Override
            public Fragment getItem(int position) {
                return fragments[position];
            }

            @Override
            public int getCount() {
                return title.length;
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return title[position];
            }
        });
        tlTabs.setBackgroundColor(EnterConfig.getInstance().getGlobalColor());
        tlTabs.setupWithViewPager(pager);
    }

    private void enableDisableSwipeRefresh(boolean flag) {
        if (mRefreshView != null) {
            mRefreshView.setEnabled(flag);
        }
    }

    @Override
    public void setChildFragmentListView(ListView listView) {
        mRefreshView.setViewGroup(listView);
    }

    @Override
    public void setContactsToRefreshFinished(boolean finished) {
        contactsToRefreshFinished = true;
        if (departmentRefreshFinished && mRefreshView.isRefreshing()) {
            mRefreshView.setRefreshing(false);
        }
    }

    @Override
    public void setDepartmentRefreshFinished(boolean finished) {
        departmentRefreshFinished = true;
        if (contactsToRefreshFinished && mRefreshView.isRefreshing()) {
            mRefreshView.setRefreshing(false);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }
}
